package top.blackr.folivora.common.log.util;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.experimental.UtilityClass;
import net.dreamlu.mica.core.utils.WebUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.blackr.folivora.common.log.aspect.SysLog;
import top.blackr.folivora.common.security.auth.SecUser;
import top.blackr.folivora.common.security.auth.SecurityUtils;

import java.util.Objects;

/**
 * 系统日志工具类
 */
@UtilityClass
public class SysLogUtils {

    public SysLog getSysLog(String title) {
        // 获取请求的上下文
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        return getSysLog(request, getUsername(), title);
    }

    public SysLog getSysLog(HttpServletRequest request, String username, String title) {
        return new SysLog()
                .setTitle(title)
                .setCreateBy(username)
                .setType(LogTypeEnum.NORMAL.getType())
                .setRemoteAddr(WebUtil.getIP(request))
                .setRequestUri(URLUtil.getPath(request.getRequestURI()))
                .setMethod(request.getMethod())
                .setUserAgent(request.getHeader(HttpHeaders.USER_AGENT))
                .setParams(HttpUtil.toParams(request.getParameterMap()));
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    private String getUsername() {
        SecUser user = SecurityUtils.getUser();
        return user !=null ? user.getUsername() : "anymore";
    }

}
